package com.qianclass.talklive.app.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.qianclass.talklive.R;
import com.qianclass.talklive.app.bean.TestGroupLoginBean;
import com.qianclass.talklive.app.utils.Constant;
import com.qianclass.talklive.app.utils.DateTime;
import com.qianclass.talklive.app.utils.DoCallback;
import com.qianclass.talklive.app.utils.FileLogUtils;
import com.qianclass.talklive.app.utils.Info;
import com.qianclass.talklive.app.utils.InfoAccessImpl;
import com.qianclass.talklive.app.utils.LogUtil;
import com.qianclass.talklive.app.utils.PhoneUtil;
import com.qianclass.talklive.app.utils.StringEncrypt;
import com.qianclass.talklive.app.utils.ThreadUtils;
import com.qianclass.talklive.app.utils.ToastUtils;
import com.qianclass.talklive.app.utils.VerificationKeyUtils;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionNo;
import com.yanzhenjie.permission.PermissionYes;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;
import java.util.Locale;

/**
 * 登录页面
 *
 * @author walter
 */
public class LoginActivity extends BaseEngineEventHandlerActivity implements
        View.OnClickListener {
    public static final String TAG = "LoginActivity";
    private Context mContext;
    private static final int PHONE_STATE = 100;

    private static final int REQUEST_WRITE = 11;

    private JSONObject js;

    private String codestr;
    /**
     * 没有网络
     */
    public static final int NETWORKTYPE_INVALID = 0;
    /**
     * wap网络
     */
    public static final int NETWORKTYPE_WAP     = 1;
    /**
     * 2G网络
     */
    public static final int NETWORKTYPE_2G      = 2;
    /**
     * 3G和3G以上网络，或统称为快速网络
     */
    public static final int NETWORKTYPE_3G      = 3;
    /**
     * wifi网络
     */
    public static final int NETWORKTYPE_WIFI    = 4;
    String result_message;

    private static final int LOGIN_ERROR     = 10;
    private static final int LOGIN_ERROR_MSG = 11;
    private static final int LOGIN_SUCCESS   = 12;
    private       EditText         mVendorKeyInput;
    private       EditText         mUsernameInput;
    public        String           token;
    private       HttpUtils        utils;
    private       TelephonyManager tm;
    public static int              mNetWorkType;
    private       String           NetworkTypeStr;
    private       String           OSLanguage, brand;
    private String      currentapiVersion;
    private String      ScreenSize;
    private String      enterType;
    private String      VerificationKey;
    private TextView    mTvVersion;
    private String      versionName;
    private ProgressBar pb_loading;

    private String deviceId;
    private String userName;
    private String deviceInfoStr;
    private String deviceInformation;
    private int    layoutID;
    private Button mBt_login;
    private Button mBt_MechanismId_show;
    private String name, pwd;
    private Gson                                gson;
    private int                                 count;
    private String                              LOGIN_MECHANISM_ID = Info.MECHANISM_ID;
    private static final int REQUEST_CODE_PERMISSION_OTHER = 210;
    private static final int REQUEST_CODE_SETTING          = 300;

    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case LOGIN_ERROR:

                    Toast.makeText(LoginActivity.this, getResources().getString(R.string.login_failed), Toast.LENGTH_LONG).show();
                    pb_loading.setVisibility(View.GONE);

                    break;
                case LOGIN_ERROR_MSG:

                    Toast.makeText(LoginActivity.this, getResources().getString(R.string.login_with_wrong_info), Toast.LENGTH_LONG).show();
                    pb_loading.setVisibility(View.GONE);

                    break;
                case LOGIN_SUCCESS:

                    break;
                default:
                    break;

            }
        }
    };


    @Override
    public void onCreate(Bundle savedInstance) {
        super.onCreate(savedInstance);

        super.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        layoutID = R.layout.activity_login;
        //防止第一次进入教室学生黑屏，所以提前申请摄像头权限
        getPermission();

        if (ActivityCompat.checkSelfPermission(LoginActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            // Camera permission has not been granted.

            requestPhonePermission();

        } else {
            deviceInfo();
        }

        setContentView(layoutID);

        ((TalkApplication) getApplication()).setEngineEventHandlerActivity(this);

        /***请求网络进行登录 ***/

        utils = new HttpUtils();
        gson = new Gson();

        initViews();
        initData();

//        if (((TalkApplication) getApplication()).getUSerAccount() != null) {
//            String name = ((TalkApplication) getApplication()).getUSerAccount();
//            mUsernameInput.setText(name);
//            mUsernameInput.setSelection(name.length());
//        }
//        if (((TalkApplication) getApplication()).getUserPwd() != null) {
//            mVendorKeyInput.setText(((TalkApplication) getApplication())
//                    .getUserPwd());
//        }

    }

    @Override
    protected void onResume()
    {
        super.onResume();
        InfoAccessImpl.getInstance(mContext).setDoCallBack(new DoCallback() {
            @Override
            public void onSuccess(String info) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        userSsoLogin();
                    }
                });
            }
            @Override
            public void onFailor(String info) {

            }
        });
    }

    @Override
    protected void onDestroy() {
        Log.i("chengwenqiang","MainActivity onDestroy");

        InfoAccessImpl.getInstance(mContext).unbindAuthService();
        super.onDestroy();
    }

    private void initData() {


        // 1.获得包管理器
        PackageManager pm = getPackageManager();
        PackageInfo packageInfo;
        try {
            // 2.获得清单文件对象
            packageInfo = pm.getPackageInfo(getPackageName(), 0);
            versionName = packageInfo.versionName;
            mTvVersion.setText(versionName);
            FileLogUtils.write("Version:" + versionName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();

        }

    }


    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            //case R.id.login_login:
            case R.id.btn_login:

                if (!validateInput()) {
                    return;
                }

                ThreadUtils.runOnMainThread(new Runnable() {
                    @Override
                    public void run() {
                        pb_loading.setVisibility(View.VISIBLE);
                    }
                });


                userLogin();


                break;

            case R.id.btn_mid_show:
                ++count;
                LogUtil.i(TAG, count + "");

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (count >= 2) {
                            if (count == 5) {
                                count = 0;
                                Toast.makeText(LoginActivity.this, Info.MECHANISM_ID, Toast.LENGTH_SHORT).show();
                            }else {
                                Toast.makeText(LoginActivity.this, "只需" + (5 - count) + "步操作即可查看机构ID", Toast.LENGTH_SHORT).show();
                            }
                        }
                    }
                });

                break;
            default:

                break;
        }
    }

    private void userSsoLogin(){

        /**
         * 确定机构类型
         */

        if (Info.MECHANISM_ID.equals(Info.PublicAgencyID)) {//通用
            //LOGIN_MECHANISM_ID = Info.PublicAgencyID;
            TalkApplication.setMechanismID(Info.PublicAgencyID);
        } else if (Info.MECHANISM_ID.equals(Info.TestGroupAgencyID)) {//testgroup
            //LOGIN_MECHANISM_ID = Info.testgroup;
            TalkApplication.setMechanismID(Info.TestGroupAgencyID);
        } else if (Info.MECHANISM_ID.equals(Info.TracyClassAgencyID)) {//Tracy
            //LOGIN_MECHANISM_ID = TracyClassAgencyID;
            TalkApplication.setMechanismID(Info.TracyClassAgencyID);
        }else if (Info.MECHANISM_ID.equals(Info.TutorAgencyID)) {//Tracy
            //LOGIN_MECHANISM_ID = TracyClassAgencyID;
            TalkApplication.setMechanismID(Info.TutorAgencyID);
        } else if (Info.MECHANISM_ID.equals(Info.FeiboAgencyID)) {//Feibo
            //LOGIN_MECHANISM_ID = TracyClassAgencyID;
            TalkApplication.setMechanismID(Info.FeiboAgencyID);
        } else if (Info.MECHANISM_ID.equals(Info.SeekeryardAgencyID)) {//Feibo
            //LOGIN_MECHANISM_ID = TracyClassAgencyID;
            TalkApplication.setMechanismID(Info.SeekeryardAgencyID);
        }

        HttpUtils httpUtils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("UA", "Android");
        params.addBodyParameter("Token", InfoAccessImpl.getInstance(this).getTokenId());
        params.addBodyParameter("UserAccount", InfoAccessImpl.getInstance(this).getHottvId());

        httpUtils.send(HttpRequest.HttpMethod.POST, Constant.getSsoLoginUrl(), params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {

                LogUtil.i("MVP", "Login response " + responseInfo.result);
                try {
                    JSONObject responseJson;
                    responseJson = new JSONObject(responseInfo.result);

                    if (responseJson.has("Result")) {

                        String result = responseJson.getString("Result");
                        if (result.equals("true")) {
                            if (responseJson.has("Token")) {
                                String token = responseJson.getString("Token");
                                Gson gson = new Gson();
                                TestGroupLoginBean testGroupLoginBean = gson.fromJson(responseInfo.result, TestGroupLoginBean.class);
                                String userid = testGroupLoginBean.getUserID();
                                String userName = testGroupLoginBean.getUserName();
                                int userType = testGroupLoginBean.getUserType();
                                String userAccount = testGroupLoginBean.getUserAccount();
                                if(null!=userid) {
                                    ((TalkApplication) getApplication()).setUserID(Integer.parseInt(userid));
                                }
                                Intent intent = new Intent(LoginActivity.this, CourseInfoActivity.class);
                                intent.putExtra("token", token);
                                intent.putExtra("UserID", userid);
                                intent.putExtra("UserType", userType);
                                intent.putExtra("UserName", userName);
                                intent.putExtra("AgencyID", TalkApplication.getMechanismId());
                                intent.putExtra("UserAccount", userAccount);
                                ((TalkApplication) getApplication()).isAutoLogin(true);
//                                ((TalkApplication) getApplication()).setUserInformation(
//                                        mVendorKeyInput.getText().toString(), mUsernameInput.getText().toString());改成了分开存，注销要清空密码

                                startActivity(intent);
                                ThreadUtils.runOnMainThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        pb_loading.setVisibility(View.GONE);
                                    }
                                });
                                ((TalkApplication)getApplication()).setIsFirst(false);
                                LoginActivity.this.finish();
                            }
                        } else {
                            ThreadUtils.runOnMainThread(new Runnable() {
                                @Override
                                public void run() {
                                    pb_loading.setVisibility(View.GONE);
                                    ToastUtils.showToast(LoginActivity.this, getResources().getString(R.string.login_failed_and_check_info));
                                }
                            });
                        }

                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(HttpException e, final String s) {
                ThreadUtils.runOnMainThread(new Runnable() {
                    @Override
                    public void run() {
                        pb_loading.setVisibility(View.GONE);
//                        ToastUtils.showToast(LoginActivity.this,"登录失败,请检查账号密码是否正确!");
                        ToastUtils.showToast(LoginActivity.this, getResources().getString(R.string.login_failed_and_check_network));
                        ToastUtils.showToast(LoginActivity.this, s);
                    }
                });
            }

        });



    }

    private void userLogin() {
        //这里进行网络请求登录
        /**
         * 确定机构类型
         */

        name = mUsernameInput.getText().toString().trim();
        pwd = mVendorKeyInput.getText().toString().trim();
//        ((TalkApplication) getApplication()).setUserInformation(
//                mVendorKeyInput.getText().toString(), mUsernameInput.getText().toString());
        if (name.length() > 0) {

            String mStrUpCase = name.toUpperCase();

            if (mStrUpCase.startsWith("T_")) {

                userName = mStrUpCase.substring(2);
                //LOGIN_MECHANISM_ID = Info.TAgencyID;
                TalkApplication.setMechanismID(Info.TAgencyID);

            } else if (mStrUpCase.startsWith("ECLASS_")) {
                //userName = mStrUpCase.substring(7);
                userName = name;
                //LOGIN_MECHANISM_ID = Info.EClassAgencyID;
                TalkApplication.setMechanismID(Info.EClassAgencyID);
            } else {
                // public testgroup  tracy
                if (Info.MECHANISM_ID.equals(Info.PublicAgencyID)) {//通用
                    //LOGIN_MECHANISM_ID = Info.PublicAgencyID;
                    TalkApplication.setMechanismID(Info.PublicAgencyID);
                } else if (Info.MECHANISM_ID.equals(Info.TestGroupAgencyID)) {//testgroup
                    //LOGIN_MECHANISM_ID = Info.testgroup;
                    TalkApplication.setMechanismID(Info.TestGroupAgencyID);
                } else if (Info.MECHANISM_ID.equals(Info.TracyClassAgencyID)) {//Tracy
                    //LOGIN_MECHANISM_ID = TracyClassAgencyID;
                    TalkApplication.setMechanismID(Info.TracyClassAgencyID);
                }else if (Info.MECHANISM_ID.equals(Info.TutorAgencyID)) {//Tracy
                    //LOGIN_MECHANISM_ID = TracyClassAgencyID;
                    TalkApplication.setMechanismID(Info.TutorAgencyID);
                } else if (Info.MECHANISM_ID.equals(Info.FeiboAgencyID)) {//Feibo
                    //LOGIN_MECHANISM_ID = TracyClassAgencyID;
                    TalkApplication.setMechanismID(Info.FeiboAgencyID);
                } else if (Info.MECHANISM_ID.equals(Info.SeekeryardAgencyID)) {//Feibo
                    //LOGIN_MECHANISM_ID = TracyClassAgencyID;
                    TalkApplication.setMechanismID(Info.SeekeryardAgencyID);
                }
                userName = name;
            }

        }

        LogUtil.i("MVP", "MECHANISM_ID --> " + TalkApplication.getMechanismId());
        VerificationKeyUtils keyUtils = new VerificationKeyUtils();
        String VerificationKey = keyUtils.getVerificationKey(TalkApplication.getMechanismId());
        HttpUtils httpUtils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("UA", "Android");
        params.addBodyParameter("Version", Info.APIVERSION);
        params.addBodyParameter("UserAccount", userName);
        params.addBodyParameter("Password", pwd);
        params.addBodyParameter("VerificationKey", VerificationKey);

        FileLogUtils.write("User Login: " + Constant.getLoginUrl());
        httpUtils.send(HttpRequest.HttpMethod.POST, Constant.getLoginUrl(), params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {

                LogUtil.i("MVP", "Login response " + responseInfo.result);
                try {
                    JSONObject responseJson;
                    responseJson = new JSONObject(responseInfo.result);

                    if (responseJson.has("Result")) {

                        String result = responseJson.getString("Result");
                        if (result.equals("true")) {
                            if (responseJson.has("Token")) {
                                String token = responseJson.getString("Token");
                                Gson gson = new Gson();
                                TestGroupLoginBean testGroupLoginBean = gson.fromJson(responseInfo.result, TestGroupLoginBean.class);
                                String userid = testGroupLoginBean.getUserID();
                                String userName = testGroupLoginBean.getUserName();
                                int userType = testGroupLoginBean.getUserType();
                                String userAccount = testGroupLoginBean.getUserAccount();
                                if(null!=userid) {
                                    ((TalkApplication) getApplication()).setUserID(Integer.parseInt(userid));
                                }
                                Intent intent = new Intent(LoginActivity.this, CourseInfoActivity.class);
                                intent.putExtra("token", token);
                                intent.putExtra("UserID", userid);
                                intent.putExtra("UserType", userType);
                                intent.putExtra("UserName", userName);
                                intent.putExtra("AgencyID", TalkApplication.getMechanismId());
                                intent.putExtra("UserAccount", userAccount);
                                ((TalkApplication) getApplication()).isAutoLogin(true);
//                                ((TalkApplication) getApplication()).setUserInformation(
//                                        mVendorKeyInput.getText().toString(), mUsernameInput.getText().toString());改成了分开存，注销要清空密码

                                ((TalkApplication) getApplication()).setUserAccount(mUsernameInput.getText().toString());
                                ((TalkApplication) getApplication()).setUserPwd( mVendorKeyInput.getText().toString());
                                startActivity(intent);
                                ThreadUtils.runOnMainThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        pb_loading.setVisibility(View.GONE);
                                    }
                                });
                                ((TalkApplication)getApplication()).setIsFirst(false);
                                LoginActivity.this.finish();
                            }
                        } else {
                            ThreadUtils.runOnMainThread(new Runnable() {
                            @Override
                            public void run() {
                                pb_loading.setVisibility(View.GONE);
                                ToastUtils.showToast(LoginActivity.this, getResources().getString(R.string.login_failed_and_check_info));
                            }
                        });
                        }

                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(HttpException e, final String s) {
                ThreadUtils.runOnMainThread(new Runnable() {
                    @Override
                    public void run() {
                        pb_loading.setVisibility(View.GONE);
//                        ToastUtils.showToast(LoginActivity.this,"登录失败,请检查账号密码是否正确!");
                        ToastUtils.showToast(LoginActivity.this, getResources().getString(R.string.login_failed_and_check_network));
                        ToastUtils.showToast(LoginActivity.this, s);
                    }
                });
            }

        });

    }




    private void requestPhonePermission() {

        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.READ_PHONE_STATE)) {


            ActivityCompat.requestPermissions(LoginActivity.this,
                    new String[]{Manifest.permission.READ_PHONE_STATE},
                    PHONE_STATE);


        } else {

            // Camera permission has not been granted yet. Request it directly.
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE},
                    PHONE_STATE);
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == PHONE_STATE) {
            //获取到设备信息的权限
            if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                deviceInfo();
            }
        }
        AndPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    private void getPermission() {
        AndPermission.with(this)
                     .requestCode(REQUEST_CODE_PERMISSION_OTHER)
                     .permission(Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
                     // rationale作用是：用户拒绝一次权限，再次申请时先征求用户同意，再打开授权对话框，避免用户勾选不再提示。
                     //                .rationale((requestCode, rationale) ->
                     //                        // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                     //                        AndPermission.rationaleDialog(LiveRoomActivity.this, rationale).show()
                     //                )
                     .rationale(new RationaleListener() {
                         @Override
                         public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                             AndPermission.rationaleDialog(LoginActivity.this, rationale).show();
                         }
                     })
                     .send();
    }


    @PermissionYes(REQUEST_CODE_PERMISSION_OTHER)
    private void getMultiYes(List<String> grantedPermissions) {
        //        Toast.makeText(this, "成功拿到所需权限", Toast.LENGTH_SHORT).show();
    }

    @PermissionNo(REQUEST_CODE_PERMISSION_OTHER)
    private void getMultiNo(List<String> deniedPermissions) {
        Toast.makeText(this, getResources().getString(R.string.permission_access_failed), Toast.LENGTH_SHORT).show();

        // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
        if (AndPermission.hasAlwaysDeniedPermission(this, deniedPermissions)) {
            AndPermission.defaultSettingDialog(this, REQUEST_CODE_SETTING)
                         .setTitle(getResources().getString(R.string.friendship_tips))
                         .setMessage(getResources().getString(R.string.permissions_worning))
                         .setPositiveButton(getResources().getString(R.string.authorize_permissions))
                         .setNegativeButton(getResources().getString(R.string.denied_permissions), null)
                         .show();

            // 更多自定dialog，请看上面。
        }
    }

    private void uploadDevice() {
        /**
         * Version：字符串，接口的版本号，与本文档版本一致。
         ClientType：字符串。Windows/iOS/Android/MacOS
         Brand：字符串，设备品牌型号。
         OSVersion：字符串，平台版本
         ScreenSize：字符串，屏幕尺寸  (Width*height)
         OSLanguage：字符串，平台语言		 NetworkType：字符串，网络类型。
         *
         * */
        /*
    * 当前使用的网络类型：
    * 例如： NETWORK_TYPE_UNKNOWN  网络类型未知  0
      NETWORK_TYPE_GPRS     GPRS网络  1
      NETWORK_TYPE_EDGE     EDGE网络  2
      NETWORK_TYPE_UMTS     UMTS网络  3
      NETWORK_TYPE_HSDPA    HSDPA网络  8
      NETWORK_TYPE_HSUPA    HSUPA网络  9
      NETWORK_TYPE_HSPA     HSPA网络  10
      NETWORK_TYPE_CDMA     CDMA网络,IS95A 或 IS95B.  4
      NETWORK_TYPE_EVDO_0   EVDO网络, revision 0.  5
      NETWORK_TYPE_EVDO_A   EVDO网络, revision A.  6
      NETWORK_TYPE_1xRTT    1xRTT网络  7
    */


        deviceInfo();

        /***
         * uploadDevice：字符串。例如：”UserID=1002;UserName=Ms.
         Li;DeviceID=00-E0-70-3B-C3-D2;Brand=pc;OSVersion=win7;
         ScreenSize=1024*768;OSLanguasge=ZN;NetWordType=Wri
         ed。字符串使用 s1 加密。
         */


        deviceInfoStr = "UserID=" + "user_id" + ";UserName=" + userName + ";DeviceID=" + deviceId + ";Brand=" + brand + ";OSVersion=" + currentapiVersion + ";ScreenSize=" + ScreenSize + ";OSLanguage=" + OSLanguage + ";NetworkType=" + NetworkTypeStr;

        deviceInformation = StringEncrypt.S1Encrypt(deviceInfoStr, Info.API_EncryptionKey);

        LogUtil.i(TAG, "deviceInfoStr  " + deviceInfoStr);
        LogUtil.i(TAG, "deviceInformation  " + deviceInformation);

        HttpUtils httpUtils = new HttpUtils();
        RequestParams Params = new RequestParams();

        DateTime dateTime = new DateTime();
        String time = dateTime.getDateTime();
        VerificationKey = StringEncrypt.S1Encrypt(Info.MECHANISM_ID + "+" + time, Info.API_EncryptionKey);

        Params.addBodyParameter("Version", Info.APIVERSION);
        Params.addBodyParameter("UA", "Android");
        Params.addBodyParameter("uploadDevice", deviceInformation);
        Params.addBodyParameter("VerificationKey", VerificationKey);

        httpUtils.send(HttpRequest.HttpMethod.POST, Constant.getUserDeviceinfo(), Params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                LogUtil.i(TAG, "上传设备信息成功" + responseInfo.result);
            }

            @Override
            public void onFailure(HttpException e, String s) {
                LogUtil.i(TAG, "上传设备信息失败" + s);
            }
        });


    }

    private void deviceInfo() {
        tm = (TelephonyManager) LoginActivity.this.getSystemService(Context.TELEPHONY_SERVICE);

        OSLanguage = Locale.getDefault().getLanguage();
        LogUtil.i(TAG, "当前机子的语言为：" + OSLanguage);

        deviceId = tm.getDeviceId();

        /**
         * 为后面log日志上传准备
         */
        ((TalkApplication) getApplication()).setErrorLogFileName(name + "_" + deviceId);

        LogUtil.i(TAG, "deviceId   " + deviceId);

        brand = PhoneUtil.getBrand();

        Display display = getWindowManager().getDefaultDisplay();
        int width = display.getWidth();
        int height = display.getHeight();


        currentapiVersion = Build.VERSION.RELEASE;


        ScreenSize = height + "" + "*" + width + "";


        int netWorkType = getNetWorkType(LoginActivity.this);


        switch (netWorkType) {
            case 0:
                NetworkTypeStr = "没有网络";
                break;
            case 1:
                NetworkTypeStr = "wap";
                break;
            case 2:
                NetworkTypeStr = "2G";
                break;
            case 3:
                NetworkTypeStr = "3G";
                break;
            case 4:
                NetworkTypeStr = "WIFI";
                break;
        }
    }


    /**
     * 获取网络状态，wifi,wap,2g,3g.
     *
     * @param context 上下文
     * @return int 网络状态 {@link #NETWORKTYPE_2G},{@link #NETWORKTYPE_3G},          *{@link #NETWORKTYPE_INVALID},{@link #NETWORKTYPE_WAP}* <p>{@link #NETWORKTYPE_WIFI}
     */

    public static int getNetWorkType(Context context) {

        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();

        if (networkInfo != null && networkInfo.isConnected()) {
            String type = networkInfo.getTypeName();

            if (type.equalsIgnoreCase("WIFI")) {
                mNetWorkType = NETWORKTYPE_WIFI;
            } else if (type.equalsIgnoreCase("MOBILE")) {
                String proxyHost = android.net.Proxy.getDefaultHost();

                mNetWorkType = TextUtils.isEmpty(proxyHost)
                        ? (isFastMobileNetwork(context) ? NETWORKTYPE_3G : NETWORKTYPE_2G)
                        : NETWORKTYPE_WAP;
            }
        } else {
            mNetWorkType = NETWORKTYPE_INVALID;
        }

        return mNetWorkType;
    }


    private static boolean isFastMobileNetwork(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        switch (telephonyManager.getNetworkType()) {
            case TelephonyManager.NETWORK_TYPE_1xRTT:
                return false; // ~ 50-100 kbps
            case TelephonyManager.NETWORK_TYPE_CDMA:
                return false; // ~ 14-64 kbps
            case TelephonyManager.NETWORK_TYPE_EDGE:
                return false; // ~ 50-100 kbps
            case TelephonyManager.NETWORK_TYPE_EVDO_0:
                return true; // ~ 400-1000 kbps
            case TelephonyManager.NETWORK_TYPE_EVDO_A:
                return true; // ~ 600-1400 kbps
            case TelephonyManager.NETWORK_TYPE_GPRS:
                return false; // ~ 100 kbps
            case TelephonyManager.NETWORK_TYPE_HSDPA:
                return true; // ~ 2-14 Mbps
            case TelephonyManager.NETWORK_TYPE_HSPA:
                return true; // ~ 700-1700 kbps
            case TelephonyManager.NETWORK_TYPE_HSUPA:
                return true; // ~ 1-23 Mbps
            case TelephonyManager.NETWORK_TYPE_UMTS:
                return true; // ~ 400-7000 kbps
            case TelephonyManager.NETWORK_TYPE_EHRPD:
                return true; // ~ 1-2 Mbps
            case TelephonyManager.NETWORK_TYPE_EVDO_B:
                return true; // ~ 5 Mbps
            case TelephonyManager.NETWORK_TYPE_HSPAP:
                return true; // ~ 10-20 Mbps
            case TelephonyManager.NETWORK_TYPE_IDEN:
                return false; // ~25 kbps
            case TelephonyManager.NETWORK_TYPE_LTE:
                return true; // ~ 10+ Mbps
            case TelephonyManager.NETWORK_TYPE_UNKNOWN:
                return false;
            default:
                return false;
        }
    }

    private void initViews() {

        //mVendorKeyInput = (EditText) findViewById(R.id.login_key_input);
        //mUsernameInput = (EditText) findViewById(R.id.login_user_input);
        mUsernameInput = (EditText) findViewById(R.id.edt_username);
        mVendorKeyInput = (EditText) findViewById(R.id.edt_password);
        mTvVersion = (TextView) findViewById(R.id.tv_version);
        pb_loading = (ProgressBar) findViewById(R.id.pb_loading);

        //mBt_login = (Button) findViewById(R.id.login_login);
        mBt_login = (Button) findViewById(R.id.btn_login);
        mBt_MechanismId_show = (Button) findViewById(R.id.btn_mid_show);

        mBt_login.setOnClickListener(this);
        mBt_MechanismId_show.setOnClickListener(this);


        pb_loading.setVisibility(View.VISIBLE);

        //click = (AutoLinearLayout) findViewById(R.id.click);

        //click.setOnClickListener(this);
    }


    /**
     * 判断edittext是否为空
     *
     * @return
     */
    private boolean validateInput() {

        if (TextUtils.isEmpty(mVendorKeyInput.getText().toString())) {

            Toast.makeText(getApplicationContext(),
                    R.string.login_key_required, Toast.LENGTH_SHORT).show();
            return false;
        }

        if (TextUtils.isEmpty(mUsernameInput.getText().toString())) {

            Toast.makeText(getApplicationContext(),
                    R.string.login_user_required, Toast.LENGTH_SHORT).show();
            return false;
        }

        return true;

    }
}